<template>
  <el-dialog title="報名" v-model="signOff" width="50%" ref="dialog" :close-on-click-modal="false">
    <!-- <template #content> -->
    <div>
      <el-form ref="ruleFormRef" label-width="100px" :model="formData" :rules="rules">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="分校：">
              <div>{{ schoolName }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="課程名稱：">
              <div>{{ list.name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日期" prop="rules_date">
              <date-controls ref="datecontrol" :searchConfig="setFormConfig" @update="update" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="時間：" prop="rules_time">
              <el-time-select v-model="formData.rules_time" @change="handleTime" start="07:00" step="00:15" end="23:59"
                placeholder="任意時間點">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label=" ">
              <el-checkbox :indeterminate="isIndeterminate" v-model="weekAll" @change="handleCheckAllChange">全選
              </el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label=" ">
              <el-checkbox-group v-model="formData.weekVal" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="week in weekOptions" :label="week.value"
                  :key="week.value">{{ week.name }}</el-checkbox>
              </el-checkbox-group>
              <el-link type="warning" size="mini">星期天數注意：如取消全部選項，提交系統默認為全部選中</el-link>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教練：" prop="admin_id">
              <el-button-group>
                <el-button type="default" size="small">{{ formData.name || '暫無選擇教練' }}</el-button>
                <el-button type="default" size="small" icon="Search" @click="selectTeacher">
                </el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="課室：" prop="classroom_id">
              <el-select v-model="formData.classroom_id" @focus="handleChangeClassRoom" placeholder="請選擇">
                <el-option v-for="(item) in classroomData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可報課堂數：">
              {{ registrationNum }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" ">
              <el-button type="primary" @click="add(ruleFormRef)" :disabled="isLoading"
                :loading="isLoading">增加</el-button>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
          <el-form-item label="人數上限：">
            <el-input v-model="formData.maxNumber" type="number"></el-input>
          </el-form-item>
        </el-col> -->
          <!-- <el-col :span="12">
          <el-form-item label="可報課堂數：">
            {{formData.maxNumber-tableList.length}}
          </el-form-item>
        </el-col> -->


          <!-- <el-col :span="12">
          <el-form-item label="試堂：">
            <el-checkbox v-model="formData.auditoriumStatus" true-label="1" false-label="0"></el-checkbox>
          </el-form-item>
        </el-col> -->
        </el-row>
        <el-button @click="del" :disabled="delTableList.length === 0" class="danger-btn" type="danger"
          size="small">刪除選擇列表
        </el-button>
        <el-table v-loading="isLoading" :data="tableList" @selection-change="handleSelectionChange" border
          style="width: 100%" height="300px" size="small">
          <el-table-column fixed="left" type="selection" width="40">
          </el-table-column>
          <el-table-column prop="date" align="center" :show-overflow-tooltip="true" label="日期">
          </el-table-column>
          <el-table-column prop="time1" align="center" :show-overflow-tooltip="true" label="時間">
          </el-table-column>
          <el-table-column prop="name" align="center" :show-overflow-tooltip="true" label="教練">
          </el-table-column>
          <el-table-column prop="room" align="center" :show-overflow-tooltip="true" label="課室">
          </el-table-column>
          <!-- <el-table-column align="center" :show-overflow-tooltip="true" label="人數">
        <template #default="scope">
            <div v-if="scope.row">
          <el-input style="width: 80px;" v-model="scope.row.number"
            @input="v=>{handleSelNumber(v,scope.row, scope.$index)} " type="number" :max="scope.row.maxNumber" :min="0" size="small"></el-input>
          /{{scope.row.maxNumber}}
            </div>
        </template>
</el-table-column> -->
        </el-table>

      </el-form>
    </div>
    <!-- </template> -->
    <!-- <template #footer> -->
    <div class="flex justify-end mt-10 w-[100%]">
      <el-button @click="signOff = false">取消</el-button>
      <el-button type="primary" @click="confirm(ruleFormRef, buttonType)" color="#081F42">確定</el-button>
    </div>
    <!-- </template> -->
  </el-dialog>
  <teacher ref="teacherRef" @update="getTeacher"></teacher>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { classroomList, verificationClass } from '@/http/index.js'
import { setFormConfig } from './index.js'
import teacher from '../notes/teacherDio.vue'
import { dayjs } from "element-plus";
import { message } from '@/common/function.js'
const teacherRef = ref('')
const isLoading = ref(false)
const weekAll = ref(true)
const isIndeterminate = ref(false)
const signOff = ref(false)
const ruleFormRef = ref('')
const weekOptions = reactive([{
  name: '周一',
  value: 1,
},
{
  name: '周二',
  value: 2,
},
{
  name: '周三',
  value: 3,
},
{
  name: '周四',
  value: 4,
},
{
  name: '周五',
  value: 5,
},
{
  name: '周六',
  value: 6,
},
{
  name: '周日',
  value: 7,
},
])
const weekValDefault = [1, 2, 3, 4, 5, 6, 7]
const schoolName = localStorage.getItem('school_name')
const formData = reactive({
  rules_date: '',
  rules_time: '',
  admin_id: '',
  classroom_id: '',
  maxNumber: 1,
  auditoriumStatus: false,
  status: 1,
  weekVal: weekValDefault,
  name: '',
  number: 1
})
const rules = reactive({
  rules_date: [{ required: true, message: "請選擇日期", trigger: ["blur", 'change'] }],
  rules_time: [{ required: true, message: "請選擇時間", trigger: ["blur", 'change'] }],
  admin_id: [{ required: true, message: "請選擇教練", trigger: ["blur", 'change'] }],
  classroom_id: [{ required: true, message: "請選擇課室", trigger: ["blur", 'change'] }],
});
const delTableList = ref([])
//刪除表格
const del = () => {
  let dels = delTableList.value.map(item => {
    return item.delid
  })
  tableList.value = tableList.value.filter(item => {
    let bool = !dels.includes(item.delid)
    if (!bool && item.hasOwnProperty('id')) {
      let obj = JSON.parse(JSON.stringify(item))
      obj.type = '-1'
      cacheList.value.push(obj)

      tableList.value = obj
    }
    return bool
  })
}
//人數修改
// const handleSelNumber = (val, item, index) =>{
//         if (Number(val) > Number(item.maxNumber)) {
//          tableList.value[index].number = item.maxNumber
//         }
//         tableList.value[index].NumberPeople = `${tableList.value[index].number}/${item.maxNumber}`
//       }
//表格多選 | 單選
const handleSelectionChange = (val) => {
  delTableList.value = val
}
const tableList = ref([])
//表單時間更新
import isoWeekday from 'dayjs/plugin/isoWeek'
dayjs.extend(isoWeekday)
const updateListDate = () => {
  let dateStart = dayjs(formData.rules_date[0]),
    dateEnd = dayjs(formData.rules_date[1]),
    dateDiff = dateEnd.diff(dateStart, 'days'),
    weekVal = formData.weekVal.length === 0 ? weekValDefault : formData.weekVal,
    newList = [],
    j = 0,
    chineseWeek = ['一', '二', '三', '四', '五', '六', '日'];
  let rules_time = formData.rules_time
  let formDatas = formData
  while (dateDiff >= j) {
    let num = dayjs(formData.rules_date[0]).add(j, 'days').isoWeekday()
    weekVal.forEach((v, i) => {
      if (v === num) {
        let obj = dayjs(dateStart).add(j, 'days')
        let strs = rules_time.split(':')
        let completeStartDate = dayjs(obj).add(parseInt(strs[0]), 'hours').add(parseInt(strs[1]), 'minutes')
          .format('YYYY-MM-DD HH:mm')
        let completeEndDate = dayjs(obj).add(parseInt(strs[0]), 'hours').add(parseInt(strs[1]) + parseInt(
          60), 'minutes').format('YYYY-MM-DD HH:mm')
        let formData = {
          ...formDatas
        }
        formData.time1 = `${completeStartDate.split(' ')[1]}-${completeEndDate.split(' ')[1]}`
        formData.date = `${dayjs(obj).format('YYYY-MM-DD')}(${chineseWeek[v - 1]})`
        formData.NumberPeople = `${formData.number}/${formData.maxNumber}`
        formData.start_time = `${completeStartDate}:00`
        formData.end_time = `${completeEndDate}:00`
        formData.type = '1'
        //   formData.status = formData.auditoriumStatus == '1' ? '試堂' : '未上課'
        formData.status == '1' ? '欠款' : '未上課'
        delete formData.rules_date
        delete formData.rules_time
        newList.unshift(formData)
      }
    })
    j++
  }
  // if (tableList.value.length + newList.length > Number(formData.maxNumber)) {
  //   return [message('報名數量超出已購課堂數!','warning')]
  // }
  return newList
}
const selWebId = () => {
  tableList.value = tableList.value.map((item, index) => {
    item.delid = index
    return item
  })
}
//添加表格
const add = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (e) => {
    if (e) {
      let listA = [...updateListDate(), ...tableList.value]
      var currentTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      listA = listA.filter((item) => dayjs(item.start_time).isAfter(dayjs(currentTime)))
      listA.map(e => {
        classroomData.value.some(item => {
          if (item.id == e.classroom_id) {
            return e.room = item.name
          }
        })
      })
      let obj = {
        school_id: school_id.value,
        student_id: student_id.value,
        data: [],
      }
      obj.data = JSON.parse(JSON.stringify(listA))
      obj.data.map(e => { e.type = 1, e.course_id = course_id.value })
      const data = await verificationClass(obj)
      if (data.code == 200) {
        if (registrationNum.value >= listA.length) {
          tableList.value = listA
          selWebId()
          message('添加成功')
        } else {
          message('報名數量超出已購課堂數!', 'warning')
        }

      }
    }
  })
  //                 listA.some(item=>{
  //   if(formData.classroom_id == item.classroom_id){
  //     item.school_name = item.name
  //     return true
  //   }
  // })
  return
  //   if (!formEl) return;
  //    formEl.validate(async (e)=>{
  let a = 0
  if (a == 0) {
    let params = {
      data: []
    }
    let listA = [...updateListDate(), ...[]]
    return
    let listB = listA.map(item => {
      let obj = JSON.parse(JSON.stringify(item))
      delete obj.webId
      return obj
    })

    listB = [...listB, ...this.cacheList]

    params.data = JSON.parse(JSON.stringify(listB))
    params.data = params.data.map(v => {
      delete v.NumberPeople
      delete v.room
      delete v.name
      v.date = v.date.split('(')[0]
      return v
    })
    params.student_id = this.params.id
    params.data = JSON.stringify(params.data)
    params.school_id = this.$store.state.user.schoolInfo.id
    this.isLoading = true
    this.$http.get('class/verificationClasshour', params).then(res => {
      this.isLoading = false
      if (res.status === 200) {
        this.tableList = listA
        this.selWebId()
        this.$message.success('添加成功！')
      } else {
        this.$message({
          duration: 3000,
          showClose: true,
          message: res.msg || '添加失敗',
          type: 'warning'
        });
      }
    }).catch(err => {
      this.isLoading = false
    })

  } else {
    return false
  }
  // })
}
const emit = defineEmits(['save'])
const confirm = async (formEl, type) => {

  emit('save', { data: [...tableList.value, ...cacheList.value], index: index.value })
  signOff.value = false
  if (!formEl) return;
  formEl.validate(async (e) => {
  })
};
const classroomData = ref([])
const handleChangeClassRoom = async () => {
  let obj = {
    school_id:school_id.value,
    page: 1,
    limit: 1000,
  }
  const data = await classroomList(obj)
  if (data.code == 200) {
    classroomData.value = data.data.data

  }
}
const dateOptions = reactive({
  start: '07:00',
  step: `00:15`, //0${diff[0]}:${(diff[1]*0.6).toString().replace('.',':')}
  end: '23:59',
})


//周日期選擇
const handleCheckedCitiesChange = (val) => {
  let checkedCount = val.length
  weekAll.value = checkedCount === weekOptions.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < weekOptions.length
}
//全選周日期選擇
const handleCheckAllChange = (val) => {
  if (val) {
    formData.weekVal = weekOptions.map(item => {
      return item.value
    })
  } else {
    formData.weekVal = []
  }
  isIndeterminate.value = false
}
const handleTime = (v) => {
  // this.formData.rules_time = v
  let strs = v.split(':')
  let nowDate = dayjs(new Date()).format('YYYY-MM-DD')
  let completeStartDate = dayjs(nowDate).add(parseInt(strs[0]), 'hours').add(parseInt(strs[1]), 'minutes').format('HH:mm')
  let completeEndDate = dayjs(nowDate).add(parseInt(strs[0]), 'hours').add(parseInt(strs[1]) + parseInt(
    60), 'minutes').format('HH:mm')
  formData.rules_time = `${completeStartDate}-${completeEndDate}`
}
const update = (e) => {
  formData.rules_date = e
}
const selectTeacher = () => {
  teacherRef.value.dialogValue = true
  teacherRef.value.TableData()
}
const getTeacher = (e) => {
  formData.name = e.ename
  formData.admin_id = e.id
}

const list = ref([])
const index = ref('')
const cacheList = ref([])
const student_id = ref('')
const school_id = ref('')
const course_id = ref('')
const dialog = ref('')
const datecontrol = ref('')
const registrationNum = ref(0)
const init = async (e, sid,scId) => {

  if (datecontrol.value !== '') {
    datecontrol.value.value = []
  }
  registrationNum.value = e.row.num
  formData.rules_date = '',
    formData.rules_time = '',
    formData.admin_id = '',
    formData.classroom_id = '',
    formData.maxNumber = 1,
    formData.auditoriumStatus = false,
    formData.status = 1,
    formData.name = '',
    formData.number = 1

  student_id.value = sid
  school_id.value = scId
  course_id.value = e.row.cid ? e.row.cid : e.row.id
  list.value = e.row
  index.value = e.index
  if (e.row.class && e.row.class.length > 0) {
    let list = []
    e.row.class.forEach(v => {
      if (v.hasOwnProperty('id') && v.type == '-1') {
        cacheList.value.push(JSON.parse(JSON.stringify(v)))
      } else {
        list.push(JSON.parse(JSON.stringify(v)))
      }
    })
    tableList.value = JSON.parse(JSON.stringify(list))
    selWebId()
  } else { tableList.value = [] }
  signOff.value = true
}
onMounted(() => {

})
defineExpose({
  signOff, init, formData
})
</script>

<style scoped lang='less'>
.danger-btn {
  margin-bottom: 5px;
}
</style>